<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Hotel_model extends CI_Model {
private $resize_img_error = "";
	private $pagination_array = array(	"rows_per_page" => "50",
										"page_now" => "1",
										"request_page" => "1",
										"startandend_gaps" => "2",
										"left_gap" => "2",
										"right_gap" => "3",
										"number_of_pages" => "12",
										"page_request_uri" => "",
										"sort_by_field" => "id",
										"sort_order" => "ASC",
										"request_uri" => ""
										);
    function __construct() {
        parent::__construct();
    }
	
/* created by	: sachintha
	 * purpose		: load_hotel_image_pagination_list
	 */		
	public function load_hotel_image_pagination_list($hotel_id=0,$param=0,$page_id=0){
		$request_uri ='/admin/hotel/gallery/'.$hotel_id.'/'.$param.'/0/';
		
		$this->pagination_array['page_now']    = $page_id;		
		$pages 			 = $this->pagination_array['number_of_pages'];
		$page_now 		 = ($this->pagination_array['page_now']=="")?1:$this->pagination_array['page_now'];
		$start_end_pages = $this->pagination_array['startandend_gaps'];
		$pre 			 = $this->pagination_array['left_gap'];
		$nex 			 = $this->pagination_array['right_gap'];
		
		if($pages<=1){
			return false;
		}
		
		$min_pages_to_apply_advanced_layout = $pre+$nex+($start_end_pages*2)+2+1;
		$out  = "";
		$out  = "<div class='pagination'>";
		
		if($page_now >1){
			$out  .= "<a href='".$request_uri.($page_now-1)."' >Previous</a>";
		}
		
		if($pages<=$min_pages_to_apply_advanced_layout){
			for($i=1;$i<=$pages;$i++){
				if($i==$page_now){
					$out .= "<a href='".$request_uri.$i."' class='current'>".$i."</a>";
				}else{
					$out .= "<a href='".$request_uri.$i."' >".$i."</a>";
				}
			}
		}else{			
			$pre_diff = $page_now-$pre;
			$nex_diff = $page_now+$nex;
			for($i=1;$i<=$pages;$i++){
				if(($i<=$start_end_pages)||($i>($pages-$start_end_pages))){
					if($i==$page_now){
						$out .= "<a href='".$request_uri.$i."' class='current'>".$i."</a>";
					}else{
						$out .= "<a href='".$request_uri.$i."'>".$i."</a>";
					}
				}else if(($pre_diff <= $i) && ($nex_diff >= $i)){
					if($i==$page_now){
						$out .= "<a href='".$request_uri.$i."' class='current'>".$i."</a>";
					}else{
						$out .= "<a href='".$request_uri.$i."' >".$i."</a>";
					}
				}else{
					$out .="###";
				}
			}
			$out = preg_replace("/[###]+/", "<b> . . . </b>", $out);
		}
		
		if($page_now < $pages){
			$out  .= "<a href='".$request_uri.($page_now+1)."' >Next</a>";
		}
		$out .= "</div>";
		return $out;
	}
	
	
	/* created by	: sachintha
	 * purpose		: load_hotel_image_list
	 */	
	public function load_hotel_image_list($hotel_id=0,$page_id=0){	
		if($hotel_id!=0){
			$sql   		= "SELECT * FROM hotel_room_images WHERE hotel_id = '".$hotel_id."' ";
			$where		= "";
			$order_by 	= "";					
			$query 		= $this->db->query($sql);		
			
			$this->pagination_array['page_now'] = ($page_id==0)?1:$page_id;
			
			$rows_per_page  = $this->pagination_array['rows_per_page'];
			$page_number	= $this->pagination_array['page_now'];
			$sort_by_field  = $this->pagination_array['sort_by_field'];
			$sort_order		= $this->pagination_array['sort_order'];			
			
			$total_rows 	 = $query->num_rows();			
			$number_of_pages = ceil($total_rows/$rows_per_page);			
			$initial_row 	 = ($page_number-1)*$rows_per_page;
			
			$this->pagination_array['number_of_pages'] = $number_of_pages;
			
			if($sort_by_field==""){
				$sort_by_field = $this->sort_by_field_arr;
			}
			
			$order_by  .= " ORDER BY ".$sort_by_field." ".$sort_order." LIMIT ".$initial_row." ,".$rows_per_page;
			$sql_limit	= $sql.$where.$order_by;
			
			$query_limit= $this->db->query($sql_limit);
			
			if($query_limit->num_rows()!=0){
				return $query_limit->result();
			}else{
				return false;
			}
		}
	}
	
	
	/* created by	: sachintha
	 * purpose		: select_hotel_image
	 */	
	public function select_hotel_image($hotel_id=0,$image_id=0){	
		if($hotel_id!=0){
			$sql = "SELECT * FROM hotel_room_images WHERE id = '".$image_id."' AND hotel_id = '".$hotel_id."'";
			$query = $this->db->query($sql); 
			return $query->result();
		}
	}
	
	
	/* created by	: sachintha
	 * purpose		: save hotel images and data
	 */	
	public function save_hotel_image($hotel_id=0,$image_id=0,$config,$image_settings_arr){
		
		$message = array();		
		if($hotel_id!=0 && trim($hotel_id)!=""){		
			if($image_id==0){				
				$sql					= "INSERT INTO hotel_room_images(hotel_id) VALUES('".$hotel_id."')";
				$query 					= $this->db->query($sql);
				$image_id           	= $this->db->insert_id();				
				$image_name 			= time()."_".$hotel_id."_".$image_id;				
				$config['file_name']	= $image_name;
				$config['remove_spaces']= TRUE;
				
				if(!file_exists("uploads/hotel/".$hotel_id)){					
					mkdir("uploads/hotel/".$hotel_id);
					mkdir("uploads/hotel/".$hotel_id."/gallery");
				}
				
				$this->load->library('upload', $config);
				$this->load->library('image_lib'); 
								
				if( ! $this->upload->do_upload('photo_image')){
					$message['error'] 			= 0;
					$message['error_details'] 	= $this->upload->display_errors();
					$sql			  			= "DELETE FROM hotel_room_images WHERE hotel_id='".$hotel_id."' AND id='".$image_id."'";
					$query 			  			= $this->db->query($sql);
					
					$this->session->set_flashdata('err', $message['error_details']);	
					redirect("/admin/hotel/gallery/".$hotel_id."/2/");
											
				}else{
					$data 			  = $this->upload->data();		
					$uploadedFiles[1] = $data;
					$data['upload_path'] = $config['upload_path'];
					
					if($data['is_image'] == 1){
						if($this->img_resize($data,$image_settings_arr)==false){
							$sql	= "DELETE FROM hotel_room_images WHERE hotel_id='".$hotel_id."' AND id='".$image_id."'";
							$query 	= $this->db->query($sql);
							$this->session->set_flashdata('err', $this->resize_img_error);	
							redirect("/admin/hotel/gallery/".$hotel_id."/2/");
						}
					}
					$this->update_hotel_image($hotel_id,$image_id,$data['file_name']);
					$message['error'] = 2;
					
					$this->session->set_flashdata('message', get_flash_message($message['error']));	
					redirect("/admin/hotel/gallery/".$hotel_id."/");
				}
			}else{
				$this->update_hotel_image($hotel_id,$image_id,0,1);
				$message['error'] = 2;
				
				$this->session->set_flashdata('message', get_flash_message($message['error']));	
				$this->session->set_flashdata('selected_tab','hotel_gallery');	
				redirect("/admin/hotel/gallery/".$hotel_id."/3/".$image_id);
			}
		}
	}
		
	
	/* created by	: sachintha
	 * purpose		: create thumbnail images
	 */	
	private function img_resize($upload,$image_settings_arr){
		    
        $this->load->library('image_lib');               
        $config['image_library'] 	= 'gd2';
        $config['source_image']    	= $upload['full_path'];
        $config['maintain_ratio']	= TRUE;
		$config['quality'] 			= '100';
        $config['width']     		= $image_settings_arr['img_max_width'];
        $config['height']    		= $image_settings_arr['img_max_height'];
        
        $this->image_lib->initialize($config); 
        
        if ( ! $this->image_lib->resize()){
			$this->resize_img_error = $this->image_lib->display_errors();
			return false;
        }        
        unset($config);
        $this->image_lib->clear();
        $this->make_thumb($upload,$image_settings_arr);
		return true;
    }
    
	
	/* created by	: sachintha
	 * purpose		: make resized thumbnail images
	 */	
    private function make_thumb($upload,$image_settings_arr)
    {
        $configthumb['image_library'] 	= 'gd2';
        $configthumb['source_image']    = $upload['full_path'];
        $configthumb['maintain_ratio'] 	= TRUE;
        $configthumb['create_thumb'] 	= TRUE;
        $configthumb['thumb_marker'] 	= "_thumb";
        $configthumb['quality'] 		= '100';
		
		$configthumb['width']     		= $image_settings_arr['img_thumb_width'];
        $configthumb['height']    		= $image_settings_arr['img_thumb_height'];

        $this->image_lib->initialize($configthumb);
        if ( ! $this->image_lib->resize()){
			$this->resize_img_error = $this->image_lib->display_errors();
			return false;
        }
        unset($configthumb);
		return true;
    } 	
	
	/* created by	: sachintha
	 * purpose		: update_hotel_image
	 */	
	private function update_hotel_image($hotel_id=0,$image_id=0,$image_name="",$is_from_edit=0){
		if($image_id!=0 && $hotel_id!=0){
			$sql_update  ="UPDATE hotel_room_images SET ";
			
			if($is_from_edit==0){
				$sql_update .=" image			= '".mysql_escape_string($image_name)."',";
			}			
			$sql_update .="	  alt_tag		= '".mysql_escape_string($_POST['alt_tag'])."',
							  description	= '".mysql_escape_string($_POST['description'])."',
							  room_type_id	= '".mysql_escape_string($_POST['room_type_id'])."',
							  title			= '".mysql_escape_string($_POST['title'])."',
							  key_words		= '".mysql_escape_string($_POST['key_words'])."'";							  			  
			$sql_update .="	WHERE id='".$image_id."' AND hotel_id = '".$hotel_id."'";
			$query 	= $this->db->query($sql_update);
			return true;
		}
		return false;
	}
	
	
	/* created by	: sachintha
	 * purpose		: delete_hotel_image
	 */			
	public function delete_hotel_image($hotel_id=0,$image_id=0,$file_path){
		
		if($hotel_id!=0){
			$sql 	= "SELECT image FROM hotel_room_images WHERE hotel_id='".$hotel_id."' AND id='".$image_id."'";	
			$query  = $this->db->query($sql);
			
			if($query->num_rows() > 0){
				$row_img   = $query->row();				
				$file_name = $file_path.$hotel_id."/gallery/".$row_img->image;
				
				$thumb_img = "";
				$thumb_img_name = "";
				
				if($row_img->image!=''){
					$thumb_img_arr 		= explode('.',$row_img->image);
					$thumb_img 			= $thumb_img_arr[0]."_thumb.".$thumb_img_arr[1];
					$thumb_img_name		= $file_path.$hotel_id."/edit/".$thumb_img_arr[0]."_thumb.".$thumb_img_arr[1];
				}
				
				$sql_del="DELETE FROM hotel_room_images WHERE hotel_id='".$hotel_id."' AND id='".$image_id."'";	
				$this->db->query($sql_del);
				
				if(file_exists($file_name) && is_file($file_name)){
					unlink($file_name);	
				}
				if(file_exists($thumb_img_name) && is_file($thumb_img_name)){
					unlink($thumb_img_name);	
				}
			}
			return true;
		}else{
			return false;	
		}	
	}
	

/*---------------------Sachintha's Gallery Configuration------------*/	


/*---------------------End Sachintha's Gallery Configuration------------*/	
	function load_city_list(){
		$sql = "SELECT * FROM `hotel_city` WHERE  is_enabled=1 ORDER BY `name`";
		$query = $this->db->query($sql); 
        return $query->result();  
	}
	
	function load_hotel_list(){
		$sql="SELECT hotel_category.name as hotel_category_name,
				  hotel.id,
				  hotel.name as hotel_name,
				  hotel_city.name as hotel_city_name,
				  hotel_type.name as hotel_type_name,
				  hotel.star_rate,
				  hotel.status_id
				FROM hotel_category
				  INNER JOIN hotel ON (hotel_category.id = hotel.category_id)
				  INNER JOIN hotel_city ON (hotel.city_id = hotel_city.id)
				  INNER JOIN hotel_type ON (hotel.hotel_type_id = hotel_type.id)
				ORDER BY hotel.id";
		$query = $this->db->query($sql); 
        return $query->result();
	}
	/*
		update hotel information
	*/
	private function update_hotel($hotel_id=0){ 
		if($hotel_id!=0){ 
			if(isset($_POST['description_location_enabled'])){
				$description_location_enabled = ($_POST['description_location_enabled']=='1'?1:0);
			}else{
				$description_location_enabled=0;
			}
			if(isset($_POST['description_accommodation_enabled'])){
				$description_accommodation_enabled = ($_POST['description_accommodation_enabled']=='1'?1:0);
			}else{
				$description_accommodation_enabled=0;
			}
			if(isset($_POST['description_facilities_enabled'])){
				$description_facilities_enabled = ($_POST['description_facilities_enabled']=='1'?1:0);
			}else{
				$description_facilities_enabled=0;
			}
			if(isset($_POST['description_excursions_enabled'])){
				$description_excursions_enabled = ($_POST['description_excursions_enabled']=='1'?1:0);
			}else{
				$description_excursions_enabled=0;
			}
			
			$sql="UPDATE hotel SET 
					  name='".mysql_escape_string($_POST['name'])."',
					  city_id=".$_POST['city_id'].",
					  category_id=".$_POST['category_id'].",
					  star_rate=".$_POST['star_rate'].",
					  hotel_type_id=".$_POST['hotel_type_id'].",
					  description_location= '".mysql_escape_string($_POST['description_location'])."',
					  description_location_enabled=".$description_location_enabled.",
					  description_accommodation='".mysql_escape_string($_POST['description_accommodation'])."',
					  description_accommodation_enabled=".$description_accommodation_enabled.",
					  description_facilities='".mysql_escape_string($_POST['description_facilities'])."',
					  description_facilities_enabled=".$description_facilities_enabled.",
					  description_excursions='".mysql_escape_string($_POST['description_excursions'])."',
					  description_excursions_enabled=".$description_excursions_enabled.",
					  domain_live='".mysql_escape_string($_POST['domain_live'])."',
					  domain_sub='".mysql_escape_string($_POST['domain_sub'])."',
					  distance_to_nearest_city='".$_POST['distance_to_nearest_city']."',
					  status_id= ".$_POST['status_id']."
				  WHERE hotel.id=".$hotel_id;
				 $this->db->query($sql);
			
			if(isset($_POST['selected_hotel_facilities']) && $_POST['selected_hotel_facilities']!=NULL){
				$sql="DELETE FROM hotel_hotel_facility WHERE hotel_id=".$hotel_id;	 
				$this->db->query($sql);
				
				$selected_hotel_facilities=$_POST['selected_hotel_facilities'];
				
				foreach($selected_hotel_facilities as $facility){
					$sql="INSERT INTO hotel_hotel_facility(hotel_id,facility_id)VALUES(".$hotel_id.",".$facility.")";
					$this->db->query($sql);	
				} 
			} 
			return true;
		}
		return false;
	}
	
	/*
		insert or update hotel
	*/
	public function save(){
		if(isset($_POST['hotel_id'])&& $_POST['hotel_id']=='0'){//insert new hotel
			$sql		= "INSERT INTO hotel() VALUES()";
			$query 		= $this->db->query($sql); 
			$hotel_id	= $this->db->insert_id(); 
			$this->update_hotel($hotel_id);
			return array($hotel_id,'i');   
		}elseif(isset($_POST['hotel_id'])&& $_POST['hotel_id']!='0'){//update existing hotel
			$hotel_id = $_POST['hotel_id'];
			$this->update_hotel($hotel_id);
			return array($hotel_id,'u');
		}else{
			return 'unknown';
		} 
	}
	
	/*
		delete a specified hotel from the system
	*/
	public function delete_hotel($hotel_id=0){
		if($hotel_id!='' && $hotel_id!=0){
			$sql="DELETE FROM hotel WHERE hotel.id=".$hotel_id;	
			$this->db->query($sql);
			return true;
		}else{
			return false;	
		}
	}
	/*
		select hotel details of a given hotel
	*/
	public function load_hotel_detail($hotel_id){
		$sql="SELECT 
			  hotel.name,
			  hotel.city_id,
			  hotel.category_id,
			  hotel.star_rate,
			  hotel.hotel_type_id,
			  hotel.description_location,
			  hotel.description_location_enabled,
			  hotel.description_accommodation,
			  hotel.description_accommodation_enabled,
			  hotel.description_facilities,
			  hotel.description_facilities_enabled,
			  hotel.description_excursions,
			  hotel.description_excursions_enabled,
			  hotel.domain_live,
			  hotel.domain_sub,
			  hotel.distance_to_nearest_city,
			  hotel.status_id
			FROM  hotel
			WHERE hotel.id=".$hotel_id;
		$query = $this->db->query($sql); 
        return $query->result();
	}
	/*
		Load facility list
	*/
	public function load_hotel_facility_list($hotel_id=0){
		
		$sql="SELECT 
		  hotel_facility.`id`,
		  hotel_facility.`name`, 
		  hotel_facility.icon 
		FROM  hotel_facility WHERE  hotel_facility.is_enabled=1";
		$query = $this->db->query($sql); 
        
		if($query->num_rows()>0){
			$hotel_facilities=array(); 
			
			foreach($query->result() as $facility){
				$hotel_facilities[$facility->id]=array('id'=>$facility->id,'name'=>$facility->name,'icon'=>$facility->icon,'checked'=>0);	
			}
		}
		
		$sql="SELECT facility_id FROM hotel_hotel_facility WHERE hotel_id=".$hotel_id;
		$query = $this->db->query($sql);
		
		if($query->num_rows()>0){
			foreach($query->result() as $selected_facilities){
				if(array_key_exists($selected_facilities->facility_id,$hotel_facilities)==true){
					$hotel_facilities[$selected_facilities->facility_id]['checked']=1;
				} 
			}
		}  
		return $hotel_facilities;
	}	
}
?>